<template>
  <VCard>
    <VToolbar color="primary" dark>
      <VToolbarTitle>我的学生管理</VToolbarTitle>
      <VSpacer />
      <VBtn icon="mdi-refresh" @click="loadStudents" :loading="loading">
        <VIcon>mdi-refresh</VIcon>
      </VBtn>
    </VToolbar>
    
    <VCardText>
      <VDataTable 
        :headers="headers" 
        :items="students" 
        :loading="loading"
        :items-per-page="10"
      >
        <template #item.student_name="{ item }">
          <div class="d-flex align-center">
            <VAvatar size="32" class="mr-3">
              <VImg src="/assets/images/avatars/avatar-1.png" alt="学生头像" />
            </VAvatar>
            <div>
              <div class="font-weight-medium">{{ item.student_name }}</div>
              <div class="text-caption text-grey">{{ item.student_username }}</div>
            </div>
          </div>
        </template>
        
        <template #item.department="{ item }">
          {{ item.department || '-' }}
        </template>
        
        <template #item.consult_count="{ item }">
          <VChip 
            :color="getConsultCountColor(item.consult_count)" 
            size="small"
          >
            {{ item.consult_count }}/8次咨询
          </VChip>
        </template>
        
        <template #item.appointment_status="{ item }">
          <VChip 
            :color="getConsultStatusColor(item.latest_conclusion, item.appointment_status)" 
            size="small"
          >
            {{ getConsultStatusText(item.latest_conclusion, item.appointment_status) }}
          </VChip>
        </template>
        
        <template #item.scheduled_time="{ item }">
          {{ formatDateTime(item.scheduled_time) }}
        </template>
        
        <template #item.action="{ item }">
          <VBtn 
            color="primary" 
            size="small" 
            @click="openRecordDialog(item)"
          >
            咨询记录
          </VBtn>
        </template>
      </VDataTable>
    </VCardText>
  </VCard>

  <!-- 咨询记录对话框 -->
  <VDialog 
    v-model="recordDialog" 
    max-width="1200px" 
    persistent
    @click:outside="closeRecordDialog"
  >
    <VCard>
      <VCardTitle class="d-flex align-center justify-space-between">
        <span>
          咨询记录 - {{ selectedStudent?.student_name }}
          <VChip 
            v-if="selectedStudent?.latest_conclusion === '结案'" 
            color="info" 
            size="small" 
            class="ml-2"
          >
            已结案
          </VChip>
        </span>
        <VBtn icon="mdi-close" variant="text" @click="closeRecordDialog" />
      </VCardTitle>
      
      <VCardText>
        <VRow>
          <!-- 左侧：学生信息 -->
          <VCol cols="12" md="4">
            <VCard variant="outlined">
              <VCardTitle>学生信息</VCardTitle>
              <VCardText>
                <div class="mb-3">
                  <strong>姓名：</strong>{{ selectedStudent?.student_name }}
                </div>
                <div class="mb-3">
                  <strong>学号：</strong>{{ selectedStudent?.student_username }}
                </div>
                <div class="mb-3">
                  <strong>院系：</strong>{{ selectedStudent?.department || '-' }}
                </div>
                <div class="mb-3">
                  <strong>班级：</strong>{{ selectedStudent?.class || '-' }}
                </div>
                <div class="mb-3">
                  <strong>联系电话：</strong>{{ selectedStudent?.student_phone || '-' }}
                </div>
                <div class="mb-3">
                  <strong>当前咨询次数：</strong>
                  <VChip 
                    :color="getConsultCountColor(selectedStudent?.consult_count || 0)" 
                    size="small"
                  >
                    {{ selectedStudent?.consult_count || 0 }}/8
                  </VChip>
                </div>
              </VCardText>
            </VCard>
            
            <!-- 添加记录按钮 -->
            <VCard variant="outlined" class="mt-3">
              <VCardText>
                <!-- 结案状态提示 -->
                <VAlert 
                  v-if="selectedStudent?.latest_conclusion === '结案'" 
                  type="info" 
                  variant="tonal" 
                  class="mb-3"
                >
                  <VIcon icon="mdi-information" class="mr-2" />
                  该学生已结案，可以查看历史咨询记录，但不能添加新记录
                </VAlert>
                
                <VBtn 
                  color="primary" 
                  block 
                  @click="openAddRecordDialog"
                  :disabled="(selectedStudent?.consult_count || 0) >= 8 || selectedStudent?.latest_conclusion === '结案'"
                >
                  添加咨询记录
                </VBtn>
                <VBtn 
                  color="warning" 
                  block 
                  class="mt-2"
                  @click="openCloseCaseDialog"
                  :disabled="!canCloseCase()"
                >
                  提前结案
                </VBtn>
                <VBtn 
                  color="success" 
                  block 
                  class="mt-2"
                  @click="openCaseReportDialog"
                  :disabled="!selectedStudent?.latest_conclusion || (selectedStudent?.latest_conclusion !== '结案' && selectedStudent?.latest_conclusion !== '脱落')"
                >
                  填写咨询结案报告
                </VBtn>
              </VCardText>
            </VCard>
          </VCol>
          
          <!-- 右侧：咨询记录列表 -->
          <VCol cols="12" md="8">
            <VCard variant="outlined">
              <VCardTitle>咨询记录历史</VCardTitle>
              <VCardText>
                <div v-if="records.length === 0" class="text-center py-8">
                  <VIcon icon="mdi-clipboard-text" size="64" color="grey" />
                  <div class="text-h6 mt-4 text-grey">暂无咨询记录</div>
                </div>
                
                <div v-else>
                  <div 
                    v-for="(record, index) in records" 
                    :key="record.id"
                    class="record-item mb-4 pa-3 border rounded"
                  >
                    <div class="d-flex justify-space-between align-start mb-2">
                      <div class="d-flex align-center">
                        <VChip 
                          :color="getConclusionColor(record.conclusion)" 
                          size="small"
                          class="mr-2"
                        >
                          {{ record.conclusion }}
                        </VChip>
                        <span class="text-caption text-grey">
                          第{{ index + 1 }}次咨询
                        </span>
                      </div>
                      <span class="text-caption text-grey">
                        {{ formatDateTime(record.visit_time) }}
                      </span>
                    </div>
                    
                    <div class="record-details">
                      <div class="mb-2">
                        <strong>风险等级：</strong>
                        <VChip 
                          :color="getRiskLevelColor(record.risk_level)" 
                          size="x-small"
                        >
                          {{ getRiskLevelText(record.risk_level) }}
                        </VChip>
                      </div>
                      <div class="mb-2">
                        <strong>问题类型：</strong>{{ record.problem_type || '-' }}
                      </div>
                      <div class="mb-2">
                        <strong>咨询笔记：</strong>
                        <div class="mt-1 pa-2 bg-grey-lighten-4 rounded">
                          {{ record.note || '无' }}
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </VCardText>
            </VCard>
          </VCol>
        </VRow>
      </VCardText>
    </VCard>
  </VDialog>

  <!-- 添加咨询记录对话框 -->
  <VDialog 
    v-model="addRecordDialog" 
    max-width="600px" 
    persistent
    @click:outside="closeAddRecordDialog"
  >
    <VCard>
      <VCardTitle>
        添加咨询记录
        <VAlert 
          v-if="selectedStudent?.latest_conclusion === '结案'" 
          type="warning" 
          variant="tonal" 
          class="mt-2"
        >
          <VIcon icon="mdi-alert" class="mr-2" />
          该学生已结案，无法添加新的咨询记录
        </VAlert>
      </VCardTitle>
      <VCardText>
        <VForm ref="recordFormRef" v-model="recordFormValid">
          <VRow>
            <VCol cols="12">
              <VTextField
                v-model="recordForm.visit_time"
                label="咨询时间"
                type="datetime-local"
                :rules="[v => !!v || '请选择咨询时间']"
                required
                :hint="getConsultTimeHint()"
                persistent-hint
              />
            </VCol>
            <VCol cols="12" sm="6">
              <VSelect
                v-model="recordForm.risk_level"
                :items="riskLevelOptions"
                label="风险等级"
                :rules="[v => !!v || '请选择风险等级']"
                required
              />
            </VCol>
            <VCol cols="12" sm="6">
              <VTextField
                v-model="recordForm.problem_type"
                label="问题类型"
                placeholder="如：学业压力、人际关系等"
                :rules="[v => !!v || '请输入问题类型']"
                required
              />
            </VCol>
            <VCol cols="12">
              <VSelect
                v-model="recordForm.conclusion"
                :items="conclusionOptions"
                label="咨询状态"
                :rules="[v => !!v || '请选择咨询状态']"
                required
              />
            </VCol>
            <VCol cols="12">
              <VTextarea
                v-model="recordForm.note"
                label="咨询笔记"
                placeholder="请详细记录本次咨询的内容、进展和建议..."
                rows="4"
                auto-grow
              />
            </VCol>
          </VRow>
        </VForm>
      </VCardText>
      <VCardActions>
        <VSpacer />
        <VBtn color="secondary" @click="closeAddRecordDialog">取消</VBtn>
        <VBtn 
          color="primary" 
          @click="submitRecord"
          :loading="submitting"
          :disabled="!recordFormValid"
        >
          提交记录
        </VBtn>
      </VCardActions>
    </VCard>
  </VDialog>

  <!-- 提前结案对话框 -->
  <VDialog 
    v-model="closeCaseDialog" 
    max-width="500px" 
    persistent
    @click:outside="closeCaseDialog = false"
  >
    <VCard>
      <VCardTitle>提前结案</VCardTitle>
      <VCardText>
        <VAlert type="warning" variant="tonal" class="mb-4">
          <VIcon icon="mdi-alert-circle" class="mr-2" />
          确定要提前结案吗？此操作不可撤销。
        </VAlert>
        
        <VTextField
          v-model="closeCaseForm.close_reason"
          label="结案原因"
          placeholder="请说明提前结案的原因..."
          :rules="[v => !!v || '请输入结案原因']"
          required
          rows="3"
          auto-grow
        />
      </VCardText>
      <VCardActions>
        <VSpacer />
        <VBtn color="secondary" @click="closeCaseDialog = false">取消</VBtn>
        <VBtn 
          color="warning" 
          @click="submitCloseCase"
          :loading="submitting"
        >
          确认结案
        </VBtn>
      </VCardActions>
    </VCard>
  </VDialog>

  <!-- 咨询结案报告对话框 -->
  <VDialog 
    v-model="caseReportDialog" 
    max-width="800px" 
    persistent
    @click:outside="closeCaseReportDialog"
  >
    <VCard>
      <VCardTitle>咨询结案报告</VCardTitle>
      <VCardText>
        <VForm ref="caseReportFormRef" v-model="caseReportFormValid">
          <VRow>
            <VCol cols="12" sm="6">
              <VTextField
                v-model="caseReportForm.name"
                label="来访者姓名"
                :rules="[v => !!v || '请输入来访者姓名']"
                required
              />
            </VCol>
            <VCol cols="12" sm="6">
              <VTextField
                v-model="caseReportForm.studentId"
                label="来访者学号"
                :rules="[v => !!v || '请输入来访者学号']"
                required
              />
            </VCol>
            <VCol cols="12" sm="6">
              <VSelect
                v-model="caseReportForm.gender"
                :items="genderOptions"
                label="来访者性别"
                :rules="[v => !!v || '请选择来访者性别']"
                required
              />
            </VCol>
            <VCol cols="12" sm="6">
              <VTextField
                v-model="caseReportForm.department"
                label="来访者院系"
                :rules="[v => !!v || '请输入来访者院系']"
                required
              />
            </VCol>
            <VCol cols="12" sm="6">
              <VTextField
                v-model="caseReportForm.phone"
                label="来访者联系电话"
                :rules="[v => !!v || '请输入来访者联系电话']"
                required
              />
            </VCol>
            <VCol cols="12" sm="6">
              <VTextField
                v-model="caseReportForm.problemType"
                label="问题类型"
                :rules="[v => !!v || '请输入问题类型']"
                required
              />
            </VCol>
            <VCol cols="12" sm="6">
              <VTextField
                v-model="caseReportForm.totalSessions"
                label="咨询总次数"
                type="number"
                :rules="[v => !!v || '请输入咨询总次数', v => v > 0 || '咨询总次数必须大于0']"
                required
              />
            </VCol>
            <VCol cols="12">
              <VTextarea
                v-model="caseReportForm.selfEvaluation"
                label="咨询效果自评"
                placeholder="请详细描述咨询效果和来访者的自我评价..."
                :rules="[v => !!v || '请输入咨询效果自评']"
                required
                rows="4"
                auto-grow
              />
            </VCol>
          </VRow>
        </VForm>
      </VCardText>
      <VCardActions>
        <VSpacer />
        <VBtn color="secondary" @click="closeCaseReportDialog">取消</VBtn>
        <VBtn 
          color="success" 
          @click="submitCaseReport"
          :loading="submitting"
          :disabled="!caseReportFormValid"
        >
          提交报告
        </VBtn>
      </VCardActions>
    </VCard>
  </VDialog>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted } from 'vue';
import { useSnackbarStore } from '@/store/snackbarStore';
import { useUserStore } from '@/store/userStore';
import { getMyStudents, getStudentRecords, submitConsultRecord, closeCase } from '@/api/consultant';
import { createCaseReport, getCaseReportByAppointmentId } from '@/api/caseReport';

const snackbarStore = useSnackbarStore();
const userStore = useUserStore();

// 响应式数据
const loading = ref(false);
const students = ref<any[]>([]);
const recordDialog = ref(false);
const addRecordDialog = ref(false);
const closeCaseDialog = ref(false);
const caseReportDialog = ref(false);
const selectedStudent = ref<any>(null);
const records = ref<any[]>([]);
const submitting = ref(false);
const recordFormValid = ref(false);
const caseReportFormValid = ref(false);
const recordFormRef = ref();
const caseReportFormRef = ref();

// 表单数据
const recordForm = reactive({
  visit_time: '',
  risk_level: '',
  problem_type: '',
  conclusion: '',
  note: ''
});

const closeCaseForm = reactive({
  close_reason: ''
});

const caseReportForm = reactive({
  name: '',
  studentId: '',
  gender: '',
  department: '',
  phone: '',
  problemType: '',
  totalSessions: 0,
  selfEvaluation: ''
});

// 表格列定义
const headers = [
  { title: '学生信息', key: 'student_name', sortable: false },
  { title: '院系', key: 'department' },
  { title: '咨询次数', key: 'consult_count' },
  { title: '咨询状态', key: 'appointment_status' },
  { title: '预约时间', key: 'scheduled_time' },
  { title: '操作', key: 'action', sortable: false }
];

// 选项数据
const riskLevelOptions = [
  { title: '低风险', value: 'LOW' },
  { title: '中风险', value: 'MEDIUM' },
  { title: '高风险', value: 'HIGH' },
  { title: '严重风险', value: 'CRITICAL' }
];

const conclusionOptions = [
  { title: '完成咨询', value: '完成咨询' },
  { title: '旷约', value: '旷约' },
  { title: '请假', value: '请假' },
  { title: '脱落', value: '脱落' },
  { title: '结案', value: '结案' }
];

const genderOptions = [
  { title: '男', value: 'M' },
  { title: '女', value: 'F' }
];

// 工具函数
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return '-';
  return new Date(dateTime).toLocaleString('zh-CN');
};

const getStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    'PENDING': 'warning',
    'APPROVED': 'info',
    'COMPLETED': 'success',
    'REJECTED': 'error',
    'CANCELED': 'grey'
  };
  return colorMap[status] || 'default';
};

const getStatusText = (status: string) => {
  const textMap: Record<string, string> = {
    'PENDING': '待审核',
    'APPROVED': '已批准',
    'COMPLETED': '已完成',
    'REJECTED': '已拒绝',
    'CANCELED': '已取消'
  };
  return textMap[status] || status;
};

const getConsultStatusColor = (conclusion: string, appointmentStatus: string) => {
  if (conclusion === '结案') return 'success';
  if (conclusion === '脱落') return 'error';
  if (conclusion === '旷约') return 'error';
  if (conclusion === '请假') return 'warning';
  if (conclusion === '完成咨询') return 'info';
  
  // 如果没有咨询记录，使用预约状态
  const colorMap: Record<string, string> = {
    'PENDING': 'warning',
    'APPROVED': 'info',
    'COMPLETED': 'success',
    'REJECTED': 'error',
    'CANCELED': 'grey'
  };
  return colorMap[appointmentStatus] || 'default';
};

const getConsultStatusText = (conclusion: string, appointmentStatus: string) => {
  if (conclusion) return conclusion;
  
  // 如果没有咨询记录，使用预约状态
  const textMap: Record<string, string> = {
    'PENDING': '待审核',
    'APPROVED': '已批准',
    'COMPLETED': '已完成',
    'REJECTED': '已拒绝',
    'CANCELED': '已取消'
  };
  return textMap[appointmentStatus] || appointmentStatus;
};

const getConsultCountColor = (count: number) => {
  if (count >= 8) return 'error';
  if (count >= 6) return 'warning';
  if (count >= 4) return 'info';
  return 'success';
};

const getRiskLevelColor = (level: string) => {
  const colorMap: Record<string, string> = {
    'LOW': 'success',
    'MEDIUM': 'warning',
    'HIGH': 'error',
    'CRITICAL': 'error'
  };
  return colorMap[level] || 'default';
};

const getRiskLevelText = (level: string) => {
  const textMap: Record<string, string> = {
    'LOW': '低',
    'MEDIUM': '中',
    'HIGH': '高',
    'CRITICAL': '严重'
  };
  return textMap[level] || level;
};

const getConclusionColor = (conclusion: string) => {
  const colorMap: Record<string, string> = {
    '完成咨询': 'success',
    '旷约': 'error',
    '请假': 'warning',
    '脱落': 'grey',
    '结案': 'info'
  };
  return colorMap[conclusion] || 'default';
};

const getAppointmentTypeColor = (type: string) => {
  const colorMap: Record<string, string> = {
    'INITIAL': 'warning',
    'CONSULT': 'primary'
  };
  return colorMap[type] || 'default';
};

const getAppointmentTypeText = (type: string) => {
  const textMap: Record<string, string> = {
    'INITIAL': '初访',
    'CONSULT': '咨询'
  };
  return textMap[type] || type;
};

// 格式化日期为本地时间字符串 (YYYY-MM-DDTHH:mm)
const formatToLocalDateTime = (date: Date): string => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  
  return `${year}-${month}-${day}T${hours}:${minutes}`;
};

// 添加一周的日期计算函数
const addOneWeek = (dateString: string): string => {
  try {
    // 解析日期字符串
    const date = new Date(dateString);
    
    // 检查日期是否有效
    if (isNaN(date.getTime())) {
      console.warn('无效的日期字符串:', dateString);
      return '';
    }
    
    // 添加7天
    const nextWeek = new Date(date);
    nextWeek.setDate(date.getDate() + 7);
    
    // 格式化为本地时间字符串
    return formatToLocalDateTime(nextWeek);
  } catch (error) {
    console.error('日期计算错误:', error);
    return '';
  }
};

// 获取咨询时间提示信息
const getConsultTimeHint = () => {
  const currentConsultCount = selectedStudent.value?.consult_count || 0;
  
  if (currentConsultCount === 0) {
    return '第1次咨询，默认设置为当前时间';
  } else if (currentConsultCount >= 1 && records.value.length > 0) {
    const lastRecord = records.value[records.value.length - 1];
    if (lastRecord && lastRecord.visit_time) {
      return `第${currentConsultCount + 1}次咨询，默认设置为上次咨询时间（${formatDateTime(lastRecord.visit_time)}）加一周`;
    }
  }
  
  return '请选择咨询时间';
};

// 检查是否可以结案
const canCloseCase = () => {
  if (!selectedStudent.value) return false;
  
  // 如果已经结案，不能重复结案
  if (selectedStudent.value.latest_conclusion === '结案') {
    return false;
  }
  
  // 必须有咨询记录才能结案
  if (!records.value || records.value.length === 0) {
    return false;
  }
  
  // 如果是第8次咨询，应该正常结案而不是提前结案
  const consultCount = selectedStudent.value.consult_count || 0;
  if (consultCount >= 8) {
    return false;
  }
  
  // 检查最新的咨询记录是否已提交
  const lastRecord = records.value[records.value.length - 1];
  if (!lastRecord || !lastRecord.visit_time) {
    return false;
  }
  
  return true;
};

// 数据加载
const loadStudents = async () => {
  loading.value = true;
  try {
    const consultantId = userStore.id;
    console.log('当前用户信息:', userStore.getCurrentUser);
    console.log('咨询师ID:', consultantId);
    
    if (!consultantId) {
      console.error('用户ID为空，用户信息:', userStore.getCurrentUser);
      snackbarStore.showMessage('用户信息获取失败', 'error');
      return;
    }
    
    console.log('开始调用API获取学生列表，咨询师ID:', consultantId);
    const response = await getMyStudents(consultantId);
    console.log('API响应:', response);
    
    if (response.data && response.data.code === 200) {
      students.value = response.data.data || [];
      console.log('获取到的学生列表:', students.value);
    } else {
      console.error('API返回错误:', response.data);
      snackbarStore.showMessage('获取学生列表失败: ' + (response.data?.message || '未知错误'), 'error');
    }
  } catch (error) {
    console.error('获取学生列表失败:', error);
    snackbarStore.showMessage('获取学生列表失败: ' + (error as Error).message, 'error');
  } finally {
    loading.value = false;
  }
};

const loadRecords = async (appointmentId: number) => {
  try {
    const response = await getStudentRecords(appointmentId);
    if (response.data && response.data.code === 200) {
      // 只查询咨询记录，并按时间倒序排列（最新的在前面）
      const allRecords = response.data.data || [];
      const consultRecords = allRecords.filter((record: any) => record.type === 'CONSULT');
      
      // 按visit_time升序排列，确保最早的记录在第一位，最新的记录在最后
      records.value = consultRecords.sort((a: any, b: any) => {
        const timeA = new Date(a.visit_time).getTime();
        const timeB = new Date(b.visit_time).getTime();
        return timeA - timeB; // 升序排列
      });
      
      console.log('加载的咨询记录（按时间倒序）:', records.value);
    } else {
      snackbarStore.showMessage('获取记录失败', 'error');
    }
  } catch (error) {
    console.error('获取记录失败:', error);
    snackbarStore.showMessage('获取记录失败', 'error');
  }
};

// 对话框操作
const openRecordDialog = async (student: any) => {
  selectedStudent.value = student;
  recordDialog.value = true;
  await loadRecords(student.appointment_id);
};

const closeRecordDialog = () => {
  recordDialog.value = false;
  selectedStudent.value = null;
  records.value = [];
};

const openAddRecordDialog = () => {
  // 检查学生是否已结案
  if (selectedStudent.value?.latest_conclusion === '结案') {
    snackbarStore.showMessage('该学生已结案，无法添加新的咨询记录', 'warning');
    return;
  }
  
  // 检查咨询次数是否已达上限
  if ((selectedStudent.value?.consult_count || 0) >= 8) {
    snackbarStore.showMessage('该学生咨询次数已达上限（8次），无法添加新的咨询记录', 'warning');
    return;
  }
  
  // 设置咨询时间：从第2次咨询开始，默认设置为上一次咨询时间加一周
  let defaultDateTime;
  const currentConsultCount = selectedStudent.value?.consult_count || 0;
  
  if (currentConsultCount >= 1 && records.value.length > 0) {
    // 从第2次咨询开始，获取最后一次咨询的时间
    const lastRecord = records.value[records.value.length - 1]; // 按时间升序，最后一条是最新的
    console.log('当前咨询次数:', currentConsultCount);
    console.log('所有咨询记录:', records.value);
    console.log('最后一次咨询记录:', lastRecord);
    
    if (lastRecord && lastRecord.visit_time) {
      console.log('上次咨询时间:', lastRecord.visit_time);
      // 使用新的日期计算函数，加一周
      defaultDateTime = addOneWeek(lastRecord.visit_time);
      console.log('计算后的下次咨询时间:', defaultDateTime);
      
      // 如果计算失败，使用当前时间作为备选
      if (!defaultDateTime) {
        console.warn('日期计算失败，使用当前时间');
        defaultDateTime = formatToLocalDateTime(new Date());
      }
    } else {
      // 如果无法获取上次咨询时间，使用当前时间
      console.warn('无法获取上次咨询时间，使用当前时间');
      defaultDateTime = formatToLocalDateTime(new Date());
    }
  } else {
    // 第1次咨询，使用当前时间
    console.log('第1次咨询，使用当前时间');
    defaultDateTime = formatToLocalDateTime(new Date());
  }
  
  recordForm.visit_time = defaultDateTime;
  recordForm.risk_level = '';
  recordForm.problem_type = '';
  recordForm.conclusion = '';
  recordForm.note = '';
  
  addRecordDialog.value = true;
};

const closeAddRecordDialog = () => {
  addRecordDialog.value = false;
};

const openCloseCaseDialog = () => {
  // 检查学生是否已结案
  if (selectedStudent.value?.latest_conclusion === '结案') {
    snackbarStore.showMessage('该学生已结案，无需重复操作', 'warning');
    return;
  }
  
  // 必须有咨询记录才能结案
  if (!records.value || records.value.length === 0) {
    snackbarStore.showMessage('学生还没有咨询记录，无法结案', 'warning');
    return;
  }
  
  // 如果是第8次咨询，应该正常结案而不是提前结案
  const consultCount = selectedStudent.value?.consult_count || 0;
  if (consultCount >= 8) {
    snackbarStore.showMessage('该学生已完成8次咨询，请通过正常流程结案', 'warning');
    return;
  }
  
  // 检查最新的咨询记录是否已提交
  const lastRecord = records.value[records.value.length - 1];
  if (!lastRecord || !lastRecord.visit_time) {
    snackbarStore.showMessage('最新的咨询记录尚未提交，无法结案', 'warning');
    return;
  }
  
  closeCaseForm.close_reason = '';
  closeCaseDialog.value = true;
};

const openCaseReportDialog = () => {
  // 检查学生是否已结案或脱落
  if (!selectedStudent.value?.latest_conclusion || 
      (selectedStudent.value?.latest_conclusion !== '结案' && selectedStudent.value?.latest_conclusion !== '脱落')) {
    snackbarStore.showMessage('只有已结案或脱落的学生才能填写结案报告', 'warning');
    return;
  }
  
  // 填充表单数据
  caseReportForm.name = selectedStudent.value.student_name || '';
  caseReportForm.studentId = selectedStudent.value.student_username || '';
  caseReportForm.gender = selectedStudent.value.gender || '';
  caseReportForm.department = selectedStudent.value.department || '';
  caseReportForm.phone = selectedStudent.value.student_phone || '';
  caseReportForm.problemType = '';
  caseReportForm.totalSessions = selectedStudent.value.consult_count || 0;
  caseReportForm.selfEvaluation = '';
  
  caseReportDialog.value = true;
};

const closeCaseReportDialog = () => {
  caseReportDialog.value = false;
};

// 提交操作
const submitRecord = async () => {
  if (!recordFormRef.value?.validate()) return;
  if (!selectedStudent.value) return;
  
  submitting.value = true;
  try {
    const consultantId = userStore.id;
    if (!consultantId) {
      snackbarStore.showMessage('用户信息获取失败', 'error');
      return;
    }
    
    const recordData = {
      appointment_id: selectedStudent.value.appointment_id,
      visitor_id: consultantId,
      visit_time: recordForm.visit_time.replace('T', ' '),
      risk_level: recordForm.risk_level,
      problem_type: recordForm.problem_type,
      conclusion: recordForm.conclusion,
      note: recordForm.note
    };
    
    const response = await submitConsultRecord(recordData);
    if (response.data && response.data.code === 200) {
      snackbarStore.showMessage('咨询记录提交成功', 'success');
      closeAddRecordDialog();
      await loadRecords(selectedStudent.value.appointment_id);
      await loadStudents(); // 刷新学生列表以更新咨询次数
    } else {
      snackbarStore.showMessage('咨询记录提交失败：' + (response.data?.message || '未知错误'), 'error');
    }
  } catch (error) {
    console.error('提交咨询记录失败:', error);
    snackbarStore.showMessage('提交咨询记录失败', 'error');
  } finally {
    submitting.value = false;
  }
};

const submitCloseCase = async () => {
  if (!closeCaseForm.close_reason.trim()) {
    snackbarStore.showMessage('请输入结案原因', 'error');
    return;
  }
  if (!selectedStudent.value) return;
  
  // 再次验证结案条件
  if (!canCloseCase()) {
    snackbarStore.showMessage('当前状态不允许结案', 'error');
    return;
  }
  
  submitting.value = true;
  try {
    const consultantId = userStore.id;
    if (!consultantId) {
      snackbarStore.showMessage('用户信息获取失败', 'error');
      return;
    }
    
    // 调用结案API（后端会自动处理结案记录的插入）
    const closeData = {
      appointment_id: selectedStudent.value.appointment_id,
      visitor_id: consultantId,
      close_reason: closeCaseForm.close_reason
    };
    
    const response = await closeCase(closeData);
    if (response.data && response.data.code === 200) {
      snackbarStore.showMessage('提前结案成功', 'success');
      closeCaseDialog.value = false;
      await loadRecords(selectedStudent.value.appointment_id);
      await loadStudents(); // 刷新学生列表
    } else {
      snackbarStore.showMessage('提前结案失败：' + (response.data?.message || '未知错误'), 'error');
    }
  } catch (error) {
    console.error('提前结案失败:', error);
    snackbarStore.showMessage('提前结案失败', 'error');
  } finally {
    submitting.value = false;
  }
};

const submitCaseReport = async () => {
  if (!caseReportFormRef.value?.validate()) return;
  if (!selectedStudent.value) return;
  
  submitting.value = true;
  try {
    // 字段全部用下划线风格，确保后端能正确解析
    const caseReportData = {
      appointment_id: selectedStudent.value.appointment_id,
      student_id: selectedStudent.value.student_id,
      name: caseReportForm.name,
      gender: caseReportForm.gender,
      department: caseReportForm.department,
      phone: caseReportForm.phone,
      problem_type: caseReportForm.problemType,
      total_sessions: caseReportForm.totalSessions,
      self_evaluation: caseReportForm.selfEvaluation
    };
    
    console.log('提交的结案报告数据:', caseReportData);
    
    const response = await createCaseReport(caseReportData);
    
    // 检查响应类型
    if (response.data instanceof Blob) {
      // 这是Word文档，创建下载链接
      const blob = new Blob([response.data], { 
        type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' 
      });
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = `结案报告_${caseReportForm.name}.docx`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
      
      snackbarStore.showMessage('结案报告提交成功，Word文档已下载', 'success');
      closeCaseReportDialog();
    } else {
      // 这是JSON响应（可能是错误信息）
      if (response.data && response.data.code === 200) {
        snackbarStore.showMessage('结案报告提交成功', 'success');
        closeCaseReportDialog();
      } else {
        snackbarStore.showMessage('结案报告提交失败：' + (response.data?.message || '未知错误'), 'error');
      }
    }
  } catch (error) {
    console.error('提交结案报告失败:', error);
    snackbarStore.showMessage('提交结案报告失败', 'error');
  } finally {
    submitting.value = false;
  }
};

// ESC键退出处理函数
const handleKeydown = (event: KeyboardEvent) => {
  if (event.key === 'Escape') {
    if (recordDialog.value) {
      closeRecordDialog();
    } else if (addRecordDialog.value) {
      closeAddRecordDialog();
    } else if (closeCaseDialog.value) {
      closeCaseDialog.value = false;
    } else if (caseReportDialog.value) {
      closeCaseReportDialog();
    }
  }
};

// 组件挂载时加载数据
onMounted(() => {
  loadStudents();
  // 添加键盘事件监听器
  document.addEventListener('keydown', handleKeydown);
});

// 组件卸载时移除事件监听器
onUnmounted(() => {
  document.removeEventListener('keydown', handleKeydown);
});
</script>

<style scoped>
.record-item {
  border: 1px solid #e0e0e0;
  transition: all 0.3s ease;
}

.record-item:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.record-details {
  font-size: 0.875rem;
}
</style> 